package com.tomshushu.doc.freedoc.modular.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tomshushu.doc.freedoc.core.exception.ServiceException;
import com.tomshushu.doc.freedoc.core.utils.SaltUtil;
import com.tomshushu.doc.freedoc.modular.project.mapper.ProjectMapper;
import com.tomshushu.doc.freedoc.modular.project.model.result.ProjectListResult;
import com.tomshushu.doc.freedoc.modular.team.mapper.TeamMapper;
import com.tomshushu.doc.freedoc.modular.teamuser.model.param.TeamUserParam;
import com.tomshushu.doc.freedoc.modular.teamuser.service.TeamUserService;
import com.tomshushu.doc.freedoc.modular.user.entity.UserEntity;
import com.tomshushu.doc.freedoc.modular.user.mapper.UserMapper;
import com.tomshushu.doc.freedoc.modular.user.model.param.AddUserParam;
import com.tomshushu.doc.freedoc.modular.user.model.param.GetProjectByTeamIdParam;
import com.tomshushu.doc.freedoc.modular.user.model.param.LoginParam;
import com.tomshushu.doc.freedoc.modular.user.model.result.AddUserReault;
import com.tomshushu.doc.freedoc.modular.user.model.result.LoginResult;
import com.tomshushu.doc.freedoc.modular.user.model.result.UserInfoResult;
import com.tomshushu.doc.freedoc.modular.user.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Resource
    private TeamMapper teamMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Lazy
    @Resource
    private TeamUserService teamUserService;

    @Override
    public AddUserReault addUser(AddUserParam params) {
        long count = this.count(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getAccount, params.getAccount()));
        if (count > 0) {
            throw new ServiceException(7001, "用户已存在");
        }
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(params, entity);
        String salt = SaltUtil.getRandomSalt();
        String password = SaltUtil.md5Encrypt(params.getAccount(), params.getPassword() + salt);
        entity.setSalt(salt);
        entity.setPassword(password);
        this.save(entity);

        if (ObjectUtil.isNotNull(params.getTeamId())) {
            // 关联用户团队关系
            TeamUserParam teamUserParam = new TeamUserParam();
            List<TeamUserParam.TeamUser> teamUserList = new ArrayList<>();
            TeamUserParam.TeamUser teamUser = new TeamUserParam.TeamUser();
            teamUser.setTeamId(params.getTeamId());
            teamUser.setUserId(entity.getUserId());
            teamUser.setType("PARTICIPANT");
            teamUserList.add(teamUser);
            teamUserParam.setTeamUserList(teamUserList);
            teamUserService.addTeamUser(teamUserParam);
        }

        AddUserReault result = new AddUserReault();
        BeanUtils.copyProperties(entity, result);
        result.setUserId(entity.getUserId());
        return result;
    }

    @Override
    public LoginResult login(LoginParam params) {
        UserEntity dbUser = this.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getAccount, params.getAccount()));
        if (ObjectUtil.isNull(dbUser)) {
            throw new ServiceException(7001, "用户不存在");
        }

        String reqMd5 = SaltUtil.md5Encrypt(params.getAccount(), params.getPassword() + dbUser.getSalt());

        if (!dbUser.getPassword().equalsIgnoreCase(reqMd5)) {
            throw new ServiceException(7002, "密码错误");
        }
        StpUtil.login(dbUser.getUserId());
        LoginResult result = new LoginResult();
        result.setToken(StpUtil.getTokenValue());
        return result;
    }

    @Override
    public void logout() {
        String userId = StpUtil.getLoginIdAsString();
        StpUtil.logout(userId);
    }

    @Override
    public UserInfoResult userInfo() {
        String userId = StpUtil.getLoginIdAsString();
        UserEntity dbUser = this.getById(userId);
        UserInfoResult result = new UserInfoResult();
        BeanUtils.copyProperties(dbUser, result);
        result.setTeamList(teamMapper.getTeamListByUserId(userId));
        return result;
    }

    @Override
    public List<ProjectListResult> getProjectListByUserIdOrTeamId(GetProjectByTeamIdParam param) {
        if (ObjectUtil.isNull(param.getTeamId())) {
            throw new ServiceException("teamId 不能为空");
        }
        String userId = StpUtil.getLoginIdAsString();
        return projectMapper.getProjectListByUserIdOrTeamId(userId, param.getTeamId());
    }

}